using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using CPlatePrintSys.Domain.Events;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using CPlatePrintSys.Infrastructure;
using CPlatePrintSys.Win.Views;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Navigation.Regions;

namespace CPlatePrintSys.Win.ViewModels
{
    public class HomeViewModel : BindableBase
    {
        private readonly IRegionManager _regionManager;
        private readonly IEventAggregator _eventAggregator;
        private readonly IWorkSpaceService _workSpaceService;
        private User _currentUser;

        private string _subTitle = string.Empty;
        public string SubTitle
        {
            get { return _subTitle; }
            set { SetProperty(ref _subTitle, value); }
        }

        // 工作空间历史记录
        private ObservableCollection<WorkSpaceRecord> _recentWorkSpaceRecords;
        public ObservableCollection<WorkSpaceRecord> RecentWorkSpaceRecords
        {
            get => _recentWorkSpaceRecords;
            set => SetProperty(ref _recentWorkSpaceRecords, value);
        }

        private bool _hasRecentRecords = false;
        public bool HasRecentRecords
        {
            get => _hasRecentRecords;
            set => SetProperty(ref _hasRecentRecords, value);
        }

        /// <summary>
        /// 导航到工作台页面的命令
        /// </summary>
        public ICommand Navigate2WorkSpaceCommand { get; }

        /// <summary>
        /// 导航到船号配置的命令
        /// </summary>
        public ICommand Navigate2ShipConfigCommand { get; }

        /// <summary>
        /// 导航到设置页面的命令
        /// </summary>
        public ICommand Navigate2SettingsCommand { get; }

        /// <summary>
        /// 导航到全局配置页面的命令
        /// </summary>
        public ICommand Navigate2GlobalConfigCommand { get; }

        /// <summary>
        /// 导航到船号配置页面的命令（无配置）
        /// </summary>
        public ICommand Navigate2ShipNoConfigComamnd { get; }

        /// <summary>
        /// 删除工作空间记录命令
        /// </summary>
        public ICommand DeleteWorkSpaceRecordCommand { get; }

        /// <summary>
        /// 清空所有历史记录命令
        /// </summary>
        public ICommand ClearAllHistoryCommand { get; }

        public HomeViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, IWorkSpaceService workSpaceService)
        {
            _regionManager = regionManager;
            _eventAggregator = eventAggregator;
            _workSpaceService = workSpaceService;

            RecentWorkSpaceRecords = new ObservableCollection<WorkSpaceRecord>();

            Navigate2WorkSpaceCommand = new DelegateCommand(NavigateToWorkSpace);
            Navigate2ShipConfigCommand = new DelegateCommand(NavigateToShipConfig);
            Navigate2SettingsCommand = new DelegateCommand(NavigateToSettings);
            Navigate2GlobalConfigCommand = new DelegateCommand(NavigateToGlobalConfig);
            DeleteWorkSpaceRecordCommand = new DelegateCommand<WorkSpaceRecord>(DeleteWorkSpaceRecord);
            ClearAllHistoryCommand = new DelegateCommand(ClearAllHistory);

            // 如果没有通过导航参数传递，则订阅事件等待
            _eventAggregator.GetEvent<UserLoggedInEvent>().Subscribe(OnUserLoggedIn, ThreadOption.UIThread, false);

            // 加载工作空间历史记录
            LoadRecentWorkSpaceRecordsAsync();
        }

        private void OnUserLoggedIn(User user)
        {
            this._currentUser = user;
        }

        private async void LoadRecentWorkSpaceRecordsAsync()
        {
            try
            {
                var records = await _workSpaceService.GetRecentWorkSpaceRecordsAsync(5);
                RecentWorkSpaceRecords.Clear();
                foreach (var record in records)
                {
                    RecentWorkSpaceRecords.Add(record);
                }

                HasRecentRecords = records.Count > 0;
            }
            catch (Exception ex)
            {
                // 如果加载失败，使用模拟数据
                LoadMockWorkSpaceRecords();
            }
        }

        private void LoadMockWorkSpaceRecords()
        {
            RecentWorkSpaceRecords.Clear();
            
            // 添加模拟数据
            RecentWorkSpaceRecords.Add(new WorkSpaceRecord
            {
                Id = 1,
                Name = "N1958",
                PreviewInfo = "(A101A、A102A、A103A......)",
                LastModifiedAt = DateTime.Now.AddHours(-2),
                CreatedBy = "admin",
                NodeCount = 15
            });

            RecentWorkSpaceRecords.Add(new WorkSpaceRecord
            {
                Id = 2,
                Name = "N1158",
                PreviewInfo = "(A101B、A102A)",
                LastModifiedAt = DateTime.Now.AddDays(-1),
                CreatedBy = "admin",
                NodeCount = 8
            });

            RecentWorkSpaceRecords.Add(new WorkSpaceRecord
            {
                Id = 3,
                Name = "N1058",
                PreviewInfo = "(A101B、A102A、A103A......)",
                LastModifiedAt = DateTime.Now.AddDays(-2),
                CreatedBy = "admin",
                NodeCount = 12
            });

            RecentWorkSpaceRecords.Add(new WorkSpaceRecord
            {
                Id = 4,
                Name = "N1919",
                PreviewInfo = "(A101B、A102A)",
                LastModifiedAt = DateTime.Now.AddDays(-3),
                CreatedBy = "admin",
                NodeCount = 6
            });

            RecentWorkSpaceRecords.Add(new WorkSpaceRecord
            {
                Id = 5,
                Name = "N1958",
                PreviewInfo = "(A101B)",
                LastModifiedAt = DateTime.Now.AddDays(-4),
                CreatedBy = "admin",
                NodeCount = 3
            });

            RaisePropertyChanged(nameof(HasRecentRecords));
        }

        private async void DeleteWorkSpaceRecord(WorkSpaceRecord record)
        {
            if (record == null) return;

            try
            {
                // 从数据库中删除工作空间
                await _workSpaceService.DeleteWorkSpaceAsync(record.Id);
                
                // 从列表中移除
                RecentWorkSpaceRecords.Remove(record);
                RaisePropertyChanged(nameof(HasRecentRecords));
            }
            catch (Exception ex)
            {
                // 如果删除失败，仅从列表中移除
                RecentWorkSpaceRecords.Remove(record);
                RaisePropertyChanged(nameof(HasRecentRecords));
            }
        }

        private async void ClearAllHistory()
        {
            try
            {
                // 清空所有工作空间记录
                var allRecords = RecentWorkSpaceRecords.ToList();
                foreach (var record in allRecords)
                {
                    await _workSpaceService.DeleteWorkSpaceAsync(record.Id);
                }
                
                RecentWorkSpaceRecords.Clear();
                RaisePropertyChanged(nameof(HasRecentRecords));
            }
            catch (Exception ex)
            {
                // 如果清空失败，仅清空列表
                RecentWorkSpaceRecords.Clear();
                RaisePropertyChanged(nameof(HasRecentRecords));
            }
        }

        private void NavigateToSettings()
        {
            var parameters = new NavigationParameters();
            parameters.Add("CurrentUser", _currentUser);
            _regionManager.RequestNavigate(ConstStrings.UI_Region_Secondary_Content, "SettingsView", parameters);
        }

        private void NavigateToShipConfig()
        {
            _regionManager.RequestNavigate(ConstStrings.UI_Region_Secondary_Content, "ShipNoConfigView");
        }

        private void NavigateToWorkSpace()
        {

            try
            {
                var vm = new AddBaseInfoViewModel(_workSpaceService, _eventAggregator);
                var dialog = new AddBaseInfoView();
                dialog.DataContext = vm;
                dialog.Owner = System.Windows.Application.Current.MainWindow;
                dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                var result = dialog.ShowDialog();
                if (result == true)
                {
                    //// 工作空间创建成功，刷新工作空间
                    //await RefreshWorkSpaceAsync();

                    // 导航到工作空间页面，并传递工作空间ID参数
                    var parameters = new Prism.Navigation.NavigationParameters();
                    parameters.Add("BaseInfo", "BaseInfo");

                    _regionManager.RequestNavigate(ConstStrings.UI_Region_Secondary_Content, "ProcessSequenceView", parameters);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建工作空间失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            ////_regionManager.RequestNavigate(ConstStrings.UI_Region_Secondary_Content, "ProcessSequenceView");
        }

        private void NavigateToGlobalConfig()
        {
            var parameters = new NavigationParameters();
            parameters.Add("CurrentUser", _currentUser);
            _regionManager.RequestNavigate(ConstStrings.UI_Region_Secondary_Content, "GlobalConfigView", parameters);
        }
    }
} 